<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

/**
 * @property int $id
 * @property int $user_id
 * @property int $test_id
 * @property int $question_id
 * @property array $answer
 * @property bool $is_right
 */
class Answer extends Model
{
    /**
     * {@inheritdoc}
     */
    protected $fillable = [
        'user_id',
        'test_id',
        'question_id',
        'answer',
        'is_right',
    ];

    /**
     * {@inheritdoc}
     */
    protected $casts = [
        'is_right' => 'boolean',
    ];

    /**
     * {@inheritdoc}
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        /** @var User $user */
        $user = Auth::user();

        if ($user) {
            $this->table = 'answers_' . $user->id % 10;
        } else {
            $this->table = 'answers';
        }
    }

    /**
     * 获取回答
     *
     * @param string $value
     * @return string[]
     */
    public function getAnswerAttribute($value)
    {
        $value = explode(',', $value);

        sort($value);

        return $value;
    }

    /**
     * 设置回答
     *
     * @param array $value
     */
    public function setAnswerAttribute($value)
    {
        $this->attributes['answer'] = implode(',', array_filter($value));
    }

    /**
     * 考题
     *
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function question()
    {
        return $this->belongsTo(Question::class);
    }
}
